package day16.myreflect03;

import java.lang.reflect.Field;

/**
 * @author Xiao
 * @date 2021/8/10
 */
public class FieldDemo02 {
    /**
     * 利用Field赋值和获取值
     * 	void set(Object obj, Object value)：给指定对象的成员变量赋值
     * 	Object get(Object obj)：获取指定对象的Field的值
     * 	如果是非public的，当权限不够（或者不确定权限够不够）时需要临时取消检查，
     *          然后再给变量赋值：setAccessible(boolean) 暴力反射。
     */
    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException {
        Class<?> clazz = Class.forName("day16.myreflect03.Student03");
        Student03 stu = new Student03();
        Student03 stu1 = new Student03("平安",21,"男",200);
        /**返回单个公共成员变量对象*/
        Field name = clazz.getField("name");
        Field age = clazz.getField("age");
        /**返回单个成员变量对象*/
        Field gender = clazz.getDeclaredField("gender");
        Field money = clazz.getDeclaredField("money");
        Object stu1Name = name.get(stu1);
        int stu1Age = (int) age.get(stu1);
        //取消检查
        gender.setAccessible(true);
        String stu1Gender = (String) gender.get(stu1);
        money.setAccessible(true);
        int stu1Money = (int) money.get(stu1);









        System.out.println(stu1Name + ", " + stu1Age + ", " + stu1Gender + ", " + stu1Money);
    }

    private static void methodSet(Student03 stu, Field name, Field age, Field gender, Field money) throws IllegalAccessException {
        name.set(stu,"阿良");
        age.set(stu, 24);
        //取消检查
        gender.setAccessible(true);
        gender.set(stu,"男");
        money.setAccessible(true);
        money.set(stu,100);
        System.out.println(stu);
    }
}
